<template>
  <div class="flex-1 flex flex-col">
    <!-- 地图顶部工具栏 -->
    <div class="bg-white border-b border-gray-200 px-4 h-[34px] flex items-center justify-between flex-shrink-0">
      <div class="flex items-center space-x-3">
        <!-- 折叠按钮 -->
        <a-tooltip :content="store.isLeftPanelCollapsed ? '展开操作面板' : '收起操作面板'" position="bottom">
          <a-button size="mini" @click="toggleLeftPanel">
            <icon-double-right v-if="store.isLeftPanelCollapsed" />
            <icon-double-left v-if="!store.isLeftPanelCollapsed" />
          </a-button>
        </a-tooltip>
        <h1 class="font-medium text-gray-900">地图预览</h1>
      </div>
    </div>
    <div id="map-container" class="flex-1"></div>
  </div>
</template>

<script setup lang="ts">
import { IconDoubleLeft, IconDoubleRight } from '@arco-design/web-vue/es/icon'
import { onMounted, watch } from 'vue'
import { useMapStore } from '../store'
import { clearSearchMarkers, initMap, renderAddressMarkers } from '../store/map'
import { searchInCurrentArea } from '../store/search'

const store = useMapStore()

const toggleLeftPanel = () => {
  store.toggleLeftPanel()
}

onMounted(() => {
  // 检查百度地图API是否加载完成
  const checkBaiduMap = () => {
    if (window.BMapGL) {
      initMap()
    } else {
      setTimeout(checkBaiduMap, 100)
    }
  }
  checkBaiduMap()
})

// 监听地图移动事件，实时搜索当前区域
watch(() => store.map, (newMap) => {
  if (newMap) {
    newMap.addEventListener('moveend', () => {
      if (store.activeTab === 'search' && store.searchKeyword) {
        searchInCurrentArea()
      }
    })
  }
})

// 监听tab切换
watch(() => store.activeTab, (newTab) => {
  if (newTab === 'list') {
    // 切换到地址列表时，清除搜索标记，显示地址标记
    clearSearchMarkers()
    renderAddressMarkers()
  }
})
</script>
